
import { _decorator, Component, Node, Label, Sprite, SpriteFrame } from 'cc';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { NATIVE_AD_TYPE } from '../../Script/Platform/SDK/HeyGameSDK/GlobalData';
import { ResUtils } from '../../Script/Platform/SDK/HeyGameSDK/ResUtils';
import { yy } from '../../Script/Utils/yySpace';
const { ccclass, property } = _decorator;

@ccclass('ListItemNativeAd')
export class ListItemNativeAd extends yyComponent {

    /*****************************************对外方法*****************************************/
    /**
     * 设置广告关闭时的回调函数
     * @param cb    广告关闭时要执行的函数，需绑定作用域
     * @param once  回调函数是否只执行一次
     */
    public setCloseCallBack(cb: Function, once: boolean = false) {
        this.adCloseCallBack = cb;
        this.closeCbOnce = once;
    }
    /**
     * 设置广告数据拉取失败时的回调函数
     * @param cb    广告拉取失败时要执行的函数，需绑定作用域
     * @param once  回调函数是否只执行一次
     */
    public setLoadFailCallBack(cb: Function, once: boolean = false) {
        this.loadFailCallBack = cb;
        this.loadFailCbOnce = once;
    }
    /**
     * 设置点击成功的回调
     * @param cb 
     */
    public setClickSuccessCallBack(cb: Function, once = false) {
        this.clickSuccessCb = cb;
        this.clickSuccessCbOnce = once;
    }

    /**刷新广告数据，显示新的广告内容 */
    public updateNativeAd() {
        this.loadNativeAd();
    }

    /*****************************************通用流程*****************************************/
    public init() {
        this.node.on(Node.EventType.TOUCH_START, this.onClick, this);
        this.loadNativeAd();
    }
    public reset() {
        this.destroyNativeAd();
        this.adData = null;
        this.adCloseCallBack = null;
        this.loadFailCallBack = null;
        this.clickSuccessCb = null;
        this.isLoadFinish = false;
    }
    public reuse() {
        // this.node.active = true;
        this.loadNativeAd();
    }
    public unuse() {
        this.destroyNativeAd();
    }

    /*****************************************内部数据*****************************************/
    //#region 内部数据
    private adId: any = null;
    private nativeAd: any = null;
    /**广告关闭时的回调函数 */
    protected adCloseCallBack: Function = null;
    /**关闭时的回调函数是否只执行一次 */
    protected closeCbOnce: boolean = false;
    /**数据拉取失败回调 */
    protected loadFailCallBack: Function = null;
    /**拉取失败回调是否只执行一次 */
    protected loadFailCbOnce: boolean = false;
    /*点击成功的回调 */
    protected clickSuccessCb: Function = null;
    /*点击成功的回调是否只执行一次*/
    protected clickSuccessCbOnce: boolean = false;
    //是否加载完成
    protected isLoadFinish = false;

    protected destroyNativeAd() {
        if (!!this.nativeAd) {
            console.log('GameNativeAd--initNativeAd');
            // console.log(this.nativeAd);
            HeyGameAdSDK.GameAdSDK.SDK.onNativeDestroy(this.nativeAd);
            this.nativeAd = null;
            this.adId = null;
        }
    }

    private loadNativeAd() {

        this.destroyNativeAd();
        this.isLoadFinish = false;
        this.node.active = false;   //等加载完成 再显示
        yy.log('loadNativeAd List Hide')
        this.nativeAd = HeyGameAdSDK.GameAdSDK.SDK.createNativeAd(NATIVE_AD_TYPE.LIST_ITEM_AD, this.onLoadNativeDataFinish.bind(this));
    }

    private onLoadNativeDataFinish(adData: any) {
        yy.log('loadNativeAd List Finish')

        if (adData) {
            this.adId = adData.adId;
            this.adData = adData;
            this.isLoadFinish = true;
            yy.log('loadNativeAd List Finish 1')
            this.showAd();
        } else {
            this.onLoadFail();
            this.isLoadFinish = false;
            yy.log('loadNativeAd List Finish 2')
            this.onBtnClose();//自动关闭
        }
    }
    protected onLoadFail() {
        let cb = this.loadFailCallBack;
        if (!!cb) {
            if (!!this.loadFailCbOnce) {
                this.loadFailCallBack = null;
            }
            cb();
        }
    }
    //#endregion

    //#region 广告显示
    @property(Node)
    adImg: Node = null;

    @property(Node)
    adLogo: Node = null;

    @property(Node)
    adTitle: Node = null;

    @property(Node)
    adDesc: Node = null;

    @property(Node)
    adIcon: Node = null;

    @property(Node)
    adClose: Node = null;
    adData = null;

    showAd(): void {
        if (!this.adData) return;
        if (this.adId != null) {
            this.node.active = true;   //等加载完成 再显示
        }
        // yy.log('this.adData:' + JSON.stringify(this.adData));
        // 加载广告图片
        this.adImg.active = false;
        this.adData.imgUrlList &&
            this.adData.imgUrlList.length > 0 &&
            ResUtils.loadImgUrl(this.adData.imgUrlList[0].split("?")[0], (texture) => {
                if (texture)
                    this.showAdImg(texture);
            });

        // 加载广告 logo
        this.adLogo.active = false;
        this.adData.logoUrl &&
            ResUtils.loadImgUrl(this.adData.logoUrl, (texture) => {
                this.showAdLogo(texture);
            });
        //显示广告名称
        if (!!this.adTitle) {
            this.adData.title && this.showAdTitle(this.adData.title);
        }
        //显示广告描述
        if (!!this.adDesc) {
            this.adData.desc && this.showAdDesc(this.adData.desc);
        }

    }

    showAdTitle(title) {
        //console.log("showAdTitle");
        this.adTitle.active = true;
        this.adTitle.getComponent(Label).string = title;
    }

    showAdDesc(desc) {
        //console.log("showAdDesc");
        this.adDesc.active = true;
        this.adDesc.getComponent(Label).string = desc;
    }

    showAdImg(texture) {
        //console.log("showAdImg");
        this.adImg.active = true;
        if (!!this.adClose) {
            this.adClose.active = true;
        }
        this.adImg.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(texture);
    }

    showAdLogo(texture) {
        //console.log("showAdLogo");
        this.adLogo.active = true;
        this.adLogo.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(texture);
    }

    showAdIcon(texture) {
        //console.log("showAdIcon");
        this.adIcon.active = true;
        this.adIcon.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(texture);
    }
    //#endregion

    /*****************************************点击回调*****************************************/
    /**点击广告 */
    protected onClick(): void {
        console.log("onNativeAdClick");
        if (this.nativeAd) {
            HeyGameAdSDK.GameAdSDK.SDK.onNativeAdClick(this.nativeAd, this.adId, (status) => {
                if (status) {
                    if (HeyGameConfig.HeyGameSDKConfig.onVIVOMiniGame) {
                        setTimeout(() => {
                            this.loadNativeAd();
                        }, 5 * 1000);
                        //奖励
                        this.clickSuccess();

                    } else {
                        this.loadNativeAd();
                        this.clickSuccess();
                    }
                }
            });
        }
    }

    protected clickSuccess() {
        //点击成功回调
        if (this.clickSuccessCb) {
            this.clickSuccessCb();
            if (this.clickSuccessCbOnce) {
                this.clickSuccessCb = null;
            }
        }
        //金币奖励
        this.emit(EventType.Common.UIEvent.playGoldAnim, {
            cb: () => {
                this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
                    attribute: "gameData.asset.gold",
                    value: 50,
                    mode: "+",
                    emit: true,
                    save: true,
                });
            },
            gold: 50,
        });
    }

    /**关闭原生广告 */
    protected onBtnClose() {
        this.destroyNativeAd();
        let cb = this.adCloseCallBack;
        if (!!cb) {
            if (!!this.closeCbOnce) {
                this.adCloseCallBack = null;
            }
            cb();
        }
        this.node.active = false;
    }
}